//
//  LBFollowVC.m
//  V-Learn
//
//  Created by Apple on 2019/1/24.
//  Copyright © 2019 yxk. All rights reserved.
//

#import "LBFollowVC.h"
#import "LBNiuwaDetailCell.h"
#import "WKHotmenModel.h"
#import "WKHotclockInfoVOListModel.h"
#import "LBRemenCell.h"
#import "LBNewsModel.h"
#import "XHWebImageAutoSize.h"
#import "UIImageView+WebCache.h"
#import <YYModel.h>
#import "WKDakaImageTextVC.h"
#import "VKRecordDetailVC.h"
#import "WKHotCell.h"
#import "WKSingleVC.h"
@interface LBFollowVC ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>

@property (nonatomic, strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger pageNums;

@end
static NSString *const cellId = @"DemoVC2Cell";
@implementation LBFollowVC
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    self.vc.canScroll = YES;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    self.vc.canScroll = NO;
}
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH-LBNAVBAR_HEIGHT) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    }
    return _tableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    //    self.tableView.estimatedRowHeight = 200;
    //    self.tableView.rowHeight = UITableViewAutomaticDimension;
    [self.tableView registerNib:[UINib nibWithNibName:cellId bundle:nil] forCellReuseIdentifier:cellId];
    [self requestDataRefresh];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickNoti:) name:@"ShequanFollow" object:nil];
}
- (void)clickNoti:(NSNotification *)notification{

//    NSDictionary * infoDic = [notification object];
//    NSString *pageStr = infoDic[@"pageStr"];
//    if ([pageStr isEqualToString:@"1"]) {
        [self requestDataRefresh];
//    }

}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}
- (void)requestDataRefresh{
    //下拉
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(setupLoadData)];
    //上拉
    //    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(setupLoadMoreData)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(setupLoadMoreData)];
    [self.tableView.mj_header beginRefreshing];
    
}
- (void)setupLoadData{
    _page = 1;
    _pageNums = 10;
    [self setupData];
}
/**
 加载更多数据
 */
- (void)setupLoadMoreData{
    
    ++(_page);
    _pageNums = 10;
    [self setupData];
}//决定footer的状态
- (void)checkFooterState{
    
    [self.tableView.mj_footer endRefreshingWithNoMoreData];
}
- (void)gotoLoginviewController{
    LBLoginVC *loginVC = [[LBLoginVC alloc] init];
    loginVC.jumpType = @"1";
    [self.navigationController pushViewController:loginVC animated:YES];
}
- (void)setupData{
    NSString *token = [UserModel getUserModel].token;
    if (token==nil||token.length==0) {
        [self gotoLoginviewController];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
        return;
    }else{
        //        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
        hud.labelText = @"正在加载...";
        [hud show:YES];
        
        token = [UserModel getUserModel].token;
        
        NSMutableDictionary *dic = @{@"token":token,@"page":[NSString stringWithFormat:@"%ld",(long)_page],@"num":[NSString stringWithFormat:@"%ld",(long)_pageNums]}.mutableCopy;
        
        VKWeakSelf(self)
         NSLog(@"字典的参数===%@",dic);
        [WYHXNetWorkService netWorkSerViceRequestWithGetUrl:WKQueryAttenUserClock_WKURL withPostParams:dic.mutableCopy withBlock:^(NSDictionary *result, NSError *error) {
            hud.hidden = YES;
            NSLog(@"关注的结果===%@",result);
            if ([result[@"code"]integerValue] == 200) {
                if (weakself.page == 1) {
                    [self.dataArray removeAllObjects];
                }
                
                for (NSDictionary *dic in result[@"data"]) {
                    WKHotmenModel *model = [WKHotmenModel mj_objectWithKeyValues:dic];
                    [self.dataArray addObject:model];
                }
                if ([result[@"data"] count] < 10) {
                    //不能加载更多数据
                    [self checkFooterState];
                    [MBProgressHUD showSuccess:@"已加载全部数据" toView:self.view];
                }else{
                    [self.tableView.mj_footer endRefreshing];
                }
            }else if([result[@"code"]integerValue] == 202){
                [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
                
                [self.dataArray removeAllObjects];
            }
            [weakself.tableView reloadData];
            
            [self.tableView.mj_header endRefreshing];
        }];
    }
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    
    WKHotmenModel *model = self.dataArray[indexPath.section];
    
    LBNiuwaDetailCell *cell = [LBNiuwaDetailCell cellWithTableView:tableView];
    if (![cell.jubaoButton respondsToSelector:@selector(clickJubaoBtn:)]) {
        [cell.jubaoButton addTarget:self action:@selector(clickJubaoBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    if ([model.isAtten isEqualToString:@"1"]) {
        [cell.followButton setTitle:@"取消关注" forState:UIControlStateNormal];
        cell.followButton.backgroundColor = [UIColor whiteColor];
        cell.followButton.layer.borderColor = rgb(153,153,153).CGColor;
        cell.followButton.layer.borderWidth = 1;
        [cell.followButton setTitleColor:rgb(153,153,153) forState:UIControlStateNormal];
    }else{
        
        [cell.followButton setTitle:@"关注" forState:UIControlStateNormal];
        cell.followButton.backgroundColor = rgb(233,84,18);
        [cell.followButton setTitleColor:rgb(255,255,255) forState:UIControlStateNormal];
        cell.followButton.layer.borderColor =rgb(233,84,18).CGColor;
        cell.followButton.layer.borderWidth = 1;
    }


    cell.selectionStyle = UITableViewCellSeparatorStyleNone;
    
    cell.followModel = model;
    cell.followButton.tag = 10123+indexPath.section;
    if (![cell.followButton respondsToSelector:@selector(clickFollow:)]) {
        [cell.followButton addTarget:self action:@selector(clickFollow:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    
    //点赞按钮
    cell.zanButton.tag =10123+indexPath.section;
    if (![cell.zanButton respondsToSelector:@selector(clickFavorite:)]) {
        [cell.zanButton addTarget:self action:@selector(clickFavorite:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    
    cell.playIcon.hidden = NO;
    if ([model.fileType isEqualToString:@"2"]) {//图片
        cell.playIcon.hidden = YES;
    }
    
    return cell;
}
#pragma mark - 点赞
-(void)clickFavorite:(UIButton *)sender {
    NSInteger index = sender.tag-10123;
    WKHotmenModel *model = self.dataArray[index];
    if ([model.fileType isEqualToString:@"2"]) {
        [self clickImageZanBtn:sender];
    }else {
        [self clickVideoZanBtn:sender];
    }
}

#pragma mark - 视频类型点赞
- (void)clickVideoZanBtn:(UIButton *)sender{
    NSInteger index = sender.tag-10123;
    NSLog(@"视频类型点赞");
    WKHotmenModel *model = self.dataArray[index];
    
    
    if ([model.fileType isEqualToString:@"2"]) {
        
    }else{
        NSString *token = [UserModel getUserModel].token;
        if ([model.isPrase isEqualToString:@"1"]) {
            [WYHXNetWorkManager post:WKCancelPraiseClock_WKURL params:@{@"token":token,@"clockId":model.clockId} completionHandler:^(id responseObj, NSError *error) {
                //            NSLog(@"%@",responseObj);
                NSString *code = responseObj[@"code"];
                if ([code integerValue]==200) {
                    //                    NSLog(@"视频取消点赞====第%ld次",index);
                    //                [self setupLoadData];
                    [MBProgressHUD showSuccess:@"取消成功" toView:self.view];
                    model.isPrase = @"0";
                    model.praiseNum = [NSString stringWithFormat:@"%d",[model.praiseNum intValue] - 1];
                    [self.dataArray replaceObjectAtIndex:index withObject:model];
                }else{
                    [MBProgressHUD showSuccess:responseObj[@"msg"] toView:self.view];
                }
                NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:index];
                [UIView performWithoutAnimation:^{
                    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
                }];
                //                [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
            }];
        }else{
            
            [WYHXNetWorkManager post:WKPraiseClock_WKURL params:@{@"token":token,@"clockId":model.clockId} completionHandler:^(id responseObj, NSError *error) {
                //            NSLog(@"%@",responseObj);
                NSString *code = responseObj[@"code"];
                if ([code integerValue]==200) {
                    //刷新数据
                    //                    NSLog(@"视频点赞====第%ld次",index);
                    //                [self setupLoadData];
                    [MBProgressHUD showSuccess:@"点赞成功" toView:self.view];
                    model.isPrase = @"1";
                    model.praiseNum = [NSString stringWithFormat:@"%d",[model.praiseNum intValue] + 1];
                    
                    [self.dataArray replaceObjectAtIndex:index withObject:model];
                }else{
                    [MBProgressHUD showSuccess:responseObj[@"msg"] toView:self.view];
                }
                NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:index];
                //                [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
                [UIView performWithoutAnimation:^{
                    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
                }];
            }];
        }
        
    }
    
}
#pragma mark - 图片类型点赞
- (void)clickImageZanBtn:(UIButton *)sender{
    NSInteger index = sender.tag-10123;
    NSLog(@"图片类型点赞");
    
    WKHotmenModel *model = self.dataArray[index];
    if ([model.fileType isEqualToString:@"2"]) {
        NSString *token = [UserModel getUserModel].token;
        if ([model.isPrase isEqualToString:@"1"]) {
            [WYHXNetWorkManager post:WKCancelPraiseClock_WKURL params:@{@"token":token,@"clockId":model.clockId} completionHandler:^(id responseObj, NSError *error) {
                //            NSLog(@"%@",responseObj);
                NSString *code = responseObj[@"code"];
                if ([code integerValue]==200) {
                    
                    NSLog(@"图片取消点赞====第%ld次",index);
                    //刷新数据
                    //                [self setupLoadData];
                    [MBProgressHUD showSuccess:@"取消成功" toView:self.view];
                    model.isPrase = @"0";
                    model.praiseNum = [NSString stringWithFormat:@"%d",[model.praiseNum intValue] - 1];
                    [self.dataArray replaceObjectAtIndex:index withObject:model];
                }else{
                    [MBProgressHUD showSuccess:responseObj[@"msg"] toView:self.view];
                }
                NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:index];
                [UIView performWithoutAnimation:^{
                    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
                }];
            }];
        }else{
            
            [WYHXNetWorkManager post:WKPraiseClock_WKURL params:@{@"token":token,@"clockId":model.clockId} completionHandler:^(id responseObj, NSError *error) {
                NSString *code = responseObj[@"code"];
                if ([code integerValue]==200) {
                    //刷新数据
                    [MBProgressHUD showSuccess:@"点赞成功" toView:self.view];
                    model.isPrase = @"1";
                    model.praiseNum = [NSString stringWithFormat:@"%d",[model.praiseNum intValue] + 1];
                    
                    [self.dataArray replaceObjectAtIndex:index withObject:model];
                }else{
                    [MBProgressHUD showSuccess:responseObj[@"msg"] toView:self.view];
                }
                NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:index];
                [UIView performWithoutAnimation:^{
                    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
                }];
            }];
        }
        
    }
    
    
}

-(void)clickFollow:(UIButton *)sender {
    NSInteger index = sender.tag-10123;
    WKHotmenModel *model = self.dataArray[index];
    
    
    if ([model.fileType isEqualToString:@"2"]) {
        [self clickImageFollowBtn:sender];
    }else {
        [self clickVideoFollowBtn:sender];
    }
}
#pragma mark - 图片里的关注按钮
- (void)clickImageFollowBtn:(UIButton *)sender{
    NSInteger index = sender.tag-10123;
    WKHotmenModel *model = self.dataArray[index];
    __weak typeof(self)weakSelf = self;
    
    NSString *token = [UserModel getUserModel].token;
    if ([model.isAtten isEqualToString:@"1"]) {
        [WYHXNetWorkManager post:WKCancelFollowniuwa_WKURL params:@{@"token":token,@"attenUserId":model.userId} completionHandler:^(id responseObj, NSError *error) {
            //            NSLog(@"%@",responseObj);
            NSString *code = responseObj[@"code"];
            NSString *msg = responseObj[@"msg"];
            if ([code integerValue]==200) {
                [MBProgressHUD showSuccess:@"取消成功" toView:self.view];
                for (int i=0; i<self.dataArray.count; i++) {
                    WKHotmenModel *model2 = self.dataArray[i];
                    if ([model.userId isEqualToString:model2.userId]) {
                        model.isAtten = @"0";
                        [self.dataArray replaceObjectAtIndex:i withObject:model];
                        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:i];
                        [UIView performWithoutAnimation:^{
                            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
                        }];
                    }
                }
                
            }else if([code integerValue]==203){
                [MBProgressHUD showSuccess:msg toView:self.view];
                return ;
            }
        }];
    }else{
        [WYHXNetWorkManager post:WKFollowniuwa_WKURL params:@{@"token":token,@"attenUserId":model.userId} completionHandler:^(id responseObj, NSError *error) {
            //            NSLog(@"%@",responseObj);
            NSString *code = responseObj[@"code"];
            NSString *msg = responseObj[@"msg"];
            if ([code integerValue]==200) {
                //刷新数据
                [MBProgressHUD showSuccess:@"关注成功" toView:self.view];
                
                for (int i=0; i<self.dataArray.count; i++) {
                    WKHotmenModel *model2 = self.dataArray[i];
                    if ([model.userId isEqualToString:model2.userId]) {
                        model.isAtten = @"1";
                        [self.dataArray replaceObjectAtIndex:i withObject:model];
                        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:i];
                        [UIView performWithoutAnimation:^{
                            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
                        }];
                    }
                }
                
            }else if([code integerValue]==203){
                [MBProgressHUD showSuccess:msg toView:self.view];
                return ;
            }
        }];
    }
}
#pragma mark - 视频里的关注按钮
- (void)clickVideoFollowBtn:(UIButton *)sender{
    NSInteger index = sender.tag-10123;
    
    WKHotmenModel *model = self.dataArray[index];
    NSString *token = [UserModel getUserModel].token;
    __weak typeof(self)weakSelf = self;
    if ([model.isAtten isEqualToString:@"1"]) {
        [WYHXNetWorkManager post:WKCancelFollowniuwa_WKURL params:@{@"token":token,@"attenUserId":model.userId} completionHandler:^(id responseObj, NSError *error) {
            //            NSLog(@"%@",responseObj);
            NSString *code = responseObj[@"code"];
            if ([code integerValue]==200) {
                //刷新数据
                //                [weakSelf setupLoadData];
                [MBProgressHUD showSuccess:@"取消成功" toView:self.view];
                //
                //                model.isAtten = @"0";
                //                [self.dataArray replaceObjectAtIndex:index withObject:model];
                //                NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:index];
                //                [UIView performWithoutAnimation:^{
                //                    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
                //                }];
                for (int i=0; i<self.dataArray.count; i++) {
                    WKHotmenModel *model2 = self.dataArray[i];
                    if ([model.userId isEqualToString:model2.userId]) {
                        model.isAtten = @"0";
                        [self.dataArray replaceObjectAtIndex:i withObject:model];
                        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:i];
                        [UIView performWithoutAnimation:^{
                            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
                        }];
                    }
                }
                
            }
        }];
    }else{
        [WYHXNetWorkManager post:WKFollowniuwa_WKURL params:@{@"token":token,@"attenUserId":model.userId} completionHandler:^(id responseObj, NSError *error) {
            
            NSString *code = responseObj[@"code"];
            if ([code integerValue]==200) {
                //刷新数据
                [MBProgressHUD showSuccess:@"关注成功" toView:self.view];
                
                for (int i=0; i<self.dataArray.count; i++) {
                    WKHotmenModel *model2 = self.dataArray[i];
                    if ([model.userId isEqualToString:model2.userId]) {
                        model.isAtten = @"1";
                        [self.dataArray replaceObjectAtIndex:i withObject:model];
                        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:i];
                        [UIView performWithoutAnimation:^{
                            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
                        }];
                    }
                }
            }
        }];
    }
}

#pragma mark - 举报功能
- (void)clickJubaoBtn:(UIButton *)sender{
    
    //@"拉黑"
    [self showActionViewWithTitle:nil message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"举报",] handler:^(UIAlertController *alertController, UIAlertAction *action, NSInteger index) {
        switch (index) {
            case 0:
            {
                NSLog(@"取消");
                
            }
                break;
            case 1:
            {
                NSLog(@"拉黑");
                WKSingleVC *vc = [[WKSingleVC alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            case 2:
            {
                NSLog(@"举报");
                WKSingleVC *vc = [[WKSingleVC alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            default:
                break;
        }
    }];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    WKHotmenModel *model = self.dataArray[indexPath.section];
    if ([model.fileType isEqualToString:@"2"]) {//图片
        return 435;
    }else{

        return 435;
    }
}


#warning TODO - 这里点击取消成功后，数据没有消失
#pragma mark - 取消关注 图片类型
- (void)clickFollowCancelImageBtn:(UIButton *)sender{
    __weak typeof(self)weakSelf = self;
    NSInteger index = sender.tag-2022;
    WKHotmenModel *model = self.dataArray[index];
    NSString *token = [UserModel getUserModel].token;
    [WYHXNetWorkManager post:WKCancelFollowniuwa_WKURL params:@{@"token":token,@"attenUserId":model.userId} completionHandler:^(id responseObj, NSError *error) {
        //        NSLog(@"%@",responseObj);
        NSString *code = responseObj[@"code"];
        if ([code integerValue]==200) {
            //刷新数据
            //            [self setupLoadData];
            [weakSelf requestDataRefresh];
            //            [self.dataArray removeObjectAtIndex:index];
            //            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:index];
            //            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }];
    
}

#pragma mark - 取消关注 视频类型
- (void)clickFollowCancelVideoBtn:(UIButton *)sender{
    NSInteger index = sender.tag-2022;
    WKHotmenModel *model = self.dataArray[index];
    NSString *token = [UserModel getUserModel].token;
    __weak typeof(self)weakSelf = self;
    [WYHXNetWorkManager post:WKCancelFollowniuwa_WKURL params:@{@"token":token,@"attenUserId":model.userId} completionHandler:^(id responseObj, NSError *error) {
        //        NSLog(@"%@",responseObj);
        NSString *code = responseObj[@"code"];
        if ([code integerValue]==200) {
            //刷新数据
            //            [self setupLoadData];
            [weakSelf requestDataRefresh];
            //            [self.dataArray removeObjectAtIndex:index];
            //            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:index];
            //            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
            //            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:index];
            //            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    WKHotmenModel *model = self.dataArray[indexPath.section];
    
    if (model.clockInfoVOList==0) {
        return;
    }
    if ([model.fileType isEqualToString:@"2"]) {
        WKDakaImageTextVC *imagetextVC = [WKDakaImageTextVC new];
        imagetextVC.model = model;
        [self.navigationController pushViewController:imagetextVC animated:YES];
    }else{//视频
        VKRecordDetailVC *detailVC = [VKRecordDetailVC new];
        detailVC.model = model;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}
@end
